package com.websuites.web.servlet.request;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.websuites.utils.StringUtil;


public class WsHttpServletRequestWrapperDistributed extends WsHttpServletRequestWrapper 
{
	protected String sProxyHost;
	protected int nProxyPort;
	protected String sProxyContextPath;
//	protected String sRealContextPath;
	protected String sNewContextPath;
	protected String sRealRequestURI;
	protected String sNewRequestURI;

	private void paserProxy(HttpServletRequest request)
	{
		sProxyHost = request.getHeader("Proxy-Host");
//		LogUtil.info("WsHttpServletRequestWrapper " + request.getRequestURL() + " Proxy-Host:" + sProxyHost);
		if (sProxyHost != null)
		{
	        String[] arrayOfString = StringUtil.split(":", sProxyHost);
	        sProxyHost = arrayOfString[0].trim();
	        nProxyPort = new Integer(arrayOfString[1].trim());
	        sProxyContextPath = arrayOfString[2].trim();
	        if (request instanceof WsHttpServletRequestWrapperDistributed)
	        {
	        	sNewContextPath = super.getContextPath();
	        	sNewRequestURI  = super.getRequestURI();
	        }
	        else
	        {
	        	sNewContextPath = sProxyContextPath + super.getContextPath();
	        	sNewRequestURI = sProxyContextPath + super.getRequestURI();
	        }
		}
//		LogUtil.info("super classname:" + super.getClass().getName() + "," + getRequestURL() + "," + sNewContextPath);		
	}
	public WsHttpServletRequestWrapperDistributed(HttpServletRequest request)
	{   		
		super(request); 
		paserProxy(request);
	}  
	
	public WsHttpServletRequestWrapperDistributed(HttpServletRequest request, HttpServletResponse response)
	{   		
		super(request, response); 
		paserProxy(request);
	}

	@Override
	public String getServerName()
	{	
		if (sProxyHost != null)
		{
			return sProxyHost;
		}
		else
		{
			return super.getServerName();
		}
	}
	
	@Override
	public int getServerPort()
	{
		if (sProxyHost != null)
		{
			return nProxyPort;
		}
		else
		{
			return super.getServerPort();
		}
	}
	
	@Override
	public String getContextPath()
	{
		if (sProxyHost != null)
		{
			return sNewContextPath;
		}
		else
		{
			return super.getContextPath();
		}
	}

	 public String getProxyContextPath()
	 {
			if (sProxyHost != null)
			{
				return sProxyContextPath;
			}
			else
			{
				return super.getContextPath();
			}
	 }

	@Override
	public String getRequestURI()
	{
		if (sProxyHost != null)
		{
			return sNewRequestURI;
		}
		else
		{
			return super.getRequestURI();
		}	
	}	
}
